import React, { Component } from 'react';
import MUtil from '../../utils/mm.jsx';
import User from '../../service/user-service';
import './index.min.css';

const _user = new User();
const _mm = new MUtil();

class Login extends Component {
	constructor(props) {
		super(props);
		this.state = {
			username: '',
			password: '',
			redirect: _mm.getUrlParam('redirect') || '/',
		};
	}

	componentWillMount() {
		document.title = '登陆 - MMALL ADMIN'
	}

	// 当用户名发生改变
	onInputChange = (e) => {
		let inputName = e.target.name,
				inputValue = e.target.value;
		this.setState({
			[inputName]: inputValue
		})
	}

	onInputKeyup = (e) => {
		if(e.keyCode === 13) {
			this.onSubmit()
		}
	}

	// 当用户提交表单
	onSubmit = () => {
		let loginInfo = {
			username: this.state.username,
			password: this.state.password
		},

		checkResult = _user.checkLoginInfo(loginInfo);
		// 验证通过
		if(checkResult.status) {
			_user.login(loginInfo)
			.then((res)=>{
				console.log(this.state.redirect)
				_mm.setStorage('userInfo', res)
				this.props.history.push(this.state.redirect);
			}, (errMsg) => {
				_mm.errorTips(errMsg)
			})
		} else {
			_mm.errorTips(checkResult.msg)
		}

	}

	render() {
		return (
			<div>
				<div className="col-md-4 col-md-offset-4">
					<div className="panel panel-default login-panel">
						<div className="panel-heading">欢迎登陆——MMALL管理系统</div>
						<div className="panel-body">

							<div>
								<div className="form-group">
									{/* <label htmlFor="exampleInputEmail1">用户名</label> */}
									<input type="text"
										className="form-control"
										placeholder="请输入用户名"
										name='username'
										onChange={e => this.onInputChange(e)} />
								</div>
								<div className="form-group">
									{/* <label htmlFor="exampleInputPassword1">密码</label> */}
									<input type="password"
										className="form-control"
										placeholder="请输入密码"
										name='password'
										onChange={e => this.onInputChange(e)}
										onKeyUp={e => this.onInputKeyup(e)}
									/>
								</div>
								<button type="submit" className="btn btn-primary btn-lg btn-block"
									onClick={e => this.onSubmit(e)}
								>登 录</button>
							</div>

						</div>
					</div>
				</div>
			</div>
		);
	}
}

export default Login;
